﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using Microsoft.Win32;

namespace Thinktecture.UIAnnotations.Behaviors
{
    public class OpenFileBehavior : TargetedTriggerAction<UIElement>
    {
        protected override void Invoke(object parameter)
        {
            var dialog = new OpenFileDialog();
            dialog.Title = this.DialogTitle;
            dialog.Filter = this.Filter;
            var result = dialog.ShowDialog();
            if (result.Value)
            {
                TextBox textBox = null;
                if (this.TargetObject is TextBox)
                    textBox = this.TargetObject as TextBox;
                else if (this.Target is TextBox)
                    textBox = this.Target as TextBox;
                if (textBox != null)
                    textBox.Text = dialog.FileName;
            }
        }
        
        public static readonly DependencyProperty DialogTitleProperty =
            DependencyProperty.Register("DialogTitle", typeof(string), typeof(OpenFileBehavior), new UIPropertyMetadata("Select a file..."));
        public string DialogTitle
        {
            get { return (string)GetValue(DialogTitleProperty); }
            set { SetValue(DialogTitleProperty, value); }
        }

        public static readonly DependencyProperty FilterProperty =
            DependencyProperty.Register("Filter", typeof(string), typeof(OpenFileBehavior), new UIPropertyMetadata("All Files|*.*"));
        public string Filter
        {
            get { return (string)GetValue(FilterProperty); }
            set { SetValue(FilterProperty, value); }
        }
    }
}
